# -*- coding: utf-8 -*-
from datetime import datetime
import pandas as pd
from sklearn.metrics import accuracy_score, f1_score, recall_score
from openai import OpenAI
import Api as api
import pandas as pd
import numpy as np
from sklearn.metrics import accuracy_score, f1_score, recall_score
from tqdm import tqdm
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 初始化 DeepSeek 客户端
client = OpenAI(api_key="sk-b6ae6c7c2ae74c01ae26d7d8ae7a503e", base_url="https://api.deepseek.com")

# 获取当前时间，格式为 YYYYMMDD_HHMM
current_time = datetime.now().strftime("%Y%m%d_%H%M")



def process_excel(file_path, simple_flag):
    """
    处理 Excel 文件，调用 API 并计算指标
    :param file_path: Excel 文件路径
    :param simple_flag: 是否进行采样
    """
    # 读取 Excel 文件
    df = pd.read_excel(file_path)

    if simple_flag:
        logging.info(f"总样本数: {len(df)}")
        df = df.sample(frac=0.03, random_state=42)  # random_state 保证每次采样结果一致
        logging.info(f"采样样本数: {len(df)}")

    # 初始化结果列
    df['pred_target'] = None
    df['pred_stance'] = None
    df['pred_opinion'] = None
    df['opinion_match'] = None

    # 遍历每一行
    for index, row in tqdm(df.iterrows(), total=len(df), desc="处理中"):
        back = row['background']
        content = row['content']

        try:
            # 调用 API
            target, stance, opinion = api.call_qw_api_without_example(back, content)

            # 保存结果
            df.at[index, 'pred_target'] = str(target) if target is not None else None
            df.at[index, 'pred_stance'] = str(stance) if stance is not None else None
            df.at[index, 'pred_opinion'] = str(opinion) if opinion is not None else None

        except Exception as e:
            logging.error(f"处理第 {index} 行时出错: {e}")

    # 保存结果到新的 Excel 文件
    current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
    output_file_path = file_path.replace('.xlsx', f'_result_{current_time}.xlsx')
    df.to_excel(output_file_path, index=False)
    logging.info(f"结果已保存到 {output_file_path}")


if __name__ == '__main__':
    # 示例
    example = """
    {
      "target": "政府",
      "stance": "支持",
      "opinion": "因为政府采取了有效的措施来控制疫情。"
    }
    """

    # 处理 Excel 文件
    # process_excel_simple('./test_data/test_data.xlsx')
    process_excel('./test_data/test_data.xlsx', False)